﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Microsoft.ManagementConsole;
using SolidQTools.SQLServerManagement;
using System.Xml;
using System.IO;

namespace SolidQ.SQLServerManagement
{
    /// <summary>
    /// The selection control class.
    /// </summary>
    public partial class SelectionControl : UserControl, IFormViewControl
    {
        SelectionFormView selectionFormView = null;
        /// <summary>
        /// Constructor
        /// </summary>
        public SelectionControl()
        {
            // Initialize the control.
            InitializeComponent();
            this.Dock = DockStyle.Fill;
          
        }
        /// <summary>
        /// Initialize.
        /// </summary>
        /// <param name="parentSelectionFormView"></param>
        void IFormViewControl.Initialize(FormView parentSelectionFormView)
        {
            selectionFormView = (SelectionFormView)parentSelectionFormView;

            // Add the actions
            selectionFormView.SelectionData.ActionsPaneItems.Clear();
            selectionFormView.SelectionData.ActionsPaneItems.Add(new Microsoft.ManagementConsole.Action("Show Selection", "Shows the Names of the selected Items in the FormView's ListView.", -1, "ShowSelection"));
        }
        /// <summary>
        /// Populate the list with the sample data.
        /// </summary>
        /// <param name="users"></param>
        public void RefreshData(string[][] users)
        {
            // Clear the list.
            //UserListView.Items.Clear();

            // Populate the list using the sample data.
            foreach (string[] user in users)
            {
                ListViewItem listViewItem = new ListViewItem();
                listViewItem.Text = user[0];
                listViewItem.SubItems.Add(user[1]);
               // UserListView.Items.Add(listViewItem);
            }
        }
        /// <summary>
        /// Show the selected items.
        /// </summary>
        public void ShowSelection()
        {
            //if (UserListView.SelectedItems == null)
            //{
            //    MessageBox.Show("There are no items selected");
            //}
            //else
            //{
            //    MessageBox.Show("Selected Users: \n" + GetSelectedUsers());
            //}
        }
        
        

        private void btnPreprocess_Click(object sender, EventArgs e)
        {
            //dreplay preprocess [-m controller] -i input_trace_file -d controller_working_dir [-c config_file] [-f status_interval]

            string controller = "-m ";
            string inputTraceFile = "-i ";
            string controllerWorkingDir = "-d ";
            string configFileOptional = "";
            string statusIntervalOptional = "";

            if (txConfigFile.Text.Length > 0)
                configFileOptional = "-c " + txConfigFile.Text;
            if (txStatusInterval.Text.Length > 0)
                statusIntervalOptional = "-f " + txStatusInterval.Text;

            controller += txControllerName.Text;
            inputTraceFile += txInputTraceFile.Text;
            controllerWorkingDir += txControllerWorkingDir.Text;

            DistributedReplayCommands DCR = new DistributedReplayCommands();
            string command = "dreplay preprocess " + controller + " " + inputTraceFile + " " + controllerWorkingDir + " " + configFileOptional + " " + statusIntervalOptional;
            //txOutput.Text =
                DCR.ExecuteCommandSync(command,txOutput);

        }
        private void btnReplay_Click(object sender, EventArgs e)
        {
            string controller = "-m ";
            string wClients = "-w ";
            string controllerWorkingDir = "-d ";
            string configFileOptional = "";
            string statusIntervalOptional = "";
            string serverOptional = "";
            
            string outputTraceOptional = cbOutputTrace.Checked ? "-o " : "";

            if (txReplayConfig.Text.Length > 0)
                configFileOptional = "-c " + txReplayConfig.Text;
            if (txReplayStatusInterval.Text.Length > 0)
                statusIntervalOptional = "-f " + txReplayStatusInterval.Text;
            if (txReplayTargetServer.Text.Length > 0)
                serverOptional = "-s " + txReplayTargetServer.Text;

            controller += txReplayController.Text;
            wClients += txClients.Text;
            controllerWorkingDir += txReplayWorkingDir.Text;

            DistributedReplayCommands DCR = new DistributedReplayCommands();
            string command = "dreplay replay " + controller + " " + controllerWorkingDir + " " + outputTraceOptional + " " + serverOptional + " " + wClients + "  "
                + configFileOptional + " " + statusIntervalOptional;
            //txOutput.Text =
            DCR.ExecuteCommandSync(command, txOutput);

        }


        private string SelectTextFile(string initialDirectory, string Filter)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = Filter;               
            dialog.InitialDirectory = initialDirectory;
            dialog.Title = "Select a text file";
            return (dialog.ShowDialog() == DialogResult.OK)
               ? dialog.FileName : null;
        }

        private void btnPreprocessPick_Click(object sender, EventArgs e)
        {

            txInputTraceFile.Text = SelectTextFile(@"C:\", "trc files (*.trc)|*.trc");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            txReplayConfig.Text = SelectTextFile(@"C:\", "Config files (*.config)|*.config|All files (*.*)|*.*");
        }

        private void btnPreprocessConfigPick_Click(object sender, EventArgs e)
        {
            txConfigFile.Text = SelectTextFile(@"C:\", "Config files (*.config)|*.config|All files (*.*)|*.*");
        }

        private void btnStatus_Click(object sender, EventArgs e)
        {
            string controller = "-m ";
            string statusIntervalOptional = "";
           
           
            if (txReplayStatusInterval.Text.Length > 0)
                statusIntervalOptional = "-f " + txReplayStatusInterval.Text;
           
            controller += txStatusControllerName.Text;
            
            DistributedReplayCommands DCR = new DistributedReplayCommands();
            string command = "dreplay status " + controller + " " + "  " + statusIntervalOptional;
            //txOutput.Text =
            DCR.ExecuteCommandSync(command, txOutput);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            string controller = "-m ";
        

            string quiet = cbQuiet.Checked ? "-q " : "";

            controller += txReplayController.Text;
            
            DistributedReplayCommands DCR = new DistributedReplayCommands();
            string command = "dreplay cancel " + controller + " " + quiet;
            //txOutput.Text =
            DCR.ExecuteCommandSync(command, txOutput);
        }

        private void btnconfigFindFile_Click(object sender, EventArgs e)
        {
            txConfigConfigFilePath.Text = SelectTextFile(@"C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn", "config files (*.config)|*.config");

            string xmlstr; 
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(txConfigConfigFilePath.Text); 
            xmlstr = xdoc.InnerXml.ToString();
            txConfigFileText.Text = IndentXMLString(xmlstr);
        }

        private static string IndentXMLString(string xml)
        {
            string outXml = string.Empty;
            MemoryStream ms = new MemoryStream();
            // Create a XMLTextWriter that will send its output to a memory stream (file)
            XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.Unicode);
            XmlDocument doc = new XmlDocument();

            try
            {
                // Load the unformatted XML text string into an instance 
                // of the XML Document Object Model (DOM)
                doc.LoadXml(xml);

                // Set the formatting property of the XML Text Writer to indented
                // the text writer is where the indenting will be performed
                xtw.Formatting = Formatting.Indented;

                // write dom xml to the xmltextwriter
                doc.WriteContentTo(xtw);
                // Flush the contents of the text writer
                // to the memory stream, which is simply a memory file
                xtw.Flush();

                // set to start of the memory stream (file)
                ms.Seek(0, SeekOrigin.Begin);
                // create a reader to read the contents of 
                // the memory stream (file)
                StreamReader sr = new StreamReader(ms);
                // return the formatted string to caller
                return sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return string.Empty;
            }
        }

        private void btnSaveConfig_Click(object sender, EventArgs e)
        {
            XmlDocument doctoSave = new XmlDocument();
            doctoSave.LoadXml(txConfigFileText.Text.Trim());
            doctoSave.Save(txConfigConfigFilePath.Text);
            txOutput.Text = "File Saved:" + txConfigConfigFilePath.Text;
        }

     

        
    } // class
} // namespace
